package com.kx.kxpicture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kx.kxpicture.constant.UserLoginConstant;
import com.kx.kxpicture.exception.BusinessException;
import com.kx.kxpicture.exception.ErrorCode;
import com.kx.kxpicture.manager.auth.StpKit;
import com.kx.kxpicture.model.dto.user.UserQueryRequestDTO;
import com.kx.kxpicture.model.dto.user.UserRegisterDTO;
import com.kx.kxpicture.model.entity.User;
import com.kx.kxpicture.model.enums.UserRoleEnum;
import com.kx.kxpicture.model.vo.UserLoginVO;
import com.kx.kxpicture.model.vo.UserVO;
import com.kx.kxpicture.service.UserService;
import com.kx.kxpicture.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kuang
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-08-14 17:29:32
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final StpKit stpKit;

    public UserServiceImpl(StpKit stpKit) {
        this.stpKit = stpKit;
    }

    @Override
    public Long userRegister(UserRegisterDTO userRegisterDTO) {
        //数据校验
        if (StrUtil.hasBlank(userRegisterDTO.getUserAccount(), userRegisterDTO.getUserPassword(), userRegisterDTO.getCheckPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        //判断是否有重复账号
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userRegisterDTO.getUserAccount());
        Long count = this.baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号已存在");
        }
        //判断两次密码是否一致
        if (!ObjUtil.equal(userRegisterDTO.getCheckPassword(), userRegisterDTO.getUserPassword())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不一致");
        }
        //密码加密
        String encryptPassword = getEncryptPassword(userRegisterDTO.getUserPassword());
        //保存
        User user = new User();
        user.setUserAccount(userRegisterDTO.getUserAccount());
        user.setUserPassword(encryptPassword);
        user.setUserName("kkx");
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean save = this.save(user);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败");
        }
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userAccount 账号
     * @param password    密码
     * @return UserLoginVO
     */
    @Override
    public UserLoginVO userLogin(String userAccount, String password, HttpServletRequest request) {
        //数据校验
        if (StrUtil.hasBlank(userAccount, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        //查询用户是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserAccount, userAccount);
        queryWrapper.eq(User::getUserPassword, getEncryptPassword(password));
        User user = this.baseMapper.selectOne(queryWrapper);
        if (ObjUtil.isNull(user)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号或密码错误");
        }
        //保存用户登录状态，封装返回数据
        request.getSession().setAttribute(UserLoginConstant.USER_SESSION_KEY, user);
        //记录用户登录态到sa-token,空间鉴权时使用
        StpKit.SPACE.login(user.getId());
        StpKit.SPACE.getSession().set(UserLoginConstant.USER_SESSION_KEY,user);
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user, userLoginVO);
        return userLoginVO;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        //判断是否登录
        Object attribute = request.getSession().getAttribute(UserLoginConstant.USER_SESSION_KEY);
        User user = (User) attribute;
        if (ObjUtil.isNull(user) || ObjUtil.isEmpty(user.getId())) {
            throw new BusinessException(ErrorCode.Not_LOGIN_ERROR);
        }
        //从数据库查询最新数据
        Long userId = user.getId();
        User userNew = this.getById(userId);
        if (userNew == null) {
            throw new BusinessException(ErrorCode.Not_LOGIN_ERROR);
        }
        return userNew;
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        Object attribute = request.getSession().getAttribute(UserLoginConstant.USER_SESSION_KEY);
        if (ObjUtil.isNull(attribute)) {
            throw new BusinessException(ErrorCode.Not_LOGIN_ERROR);
        }
        request.getSession().removeAttribute(UserLoginConstant.USER_SESSION_KEY);
        StpKit.SPACE.getSession().removeTokenSign(UserLoginConstant.USER_SESSION_KEY);
        return true;
    }

    /**
     * 加密密码
     *
     * @param userPassword 密码
     * @return
     */
    @Override
    public String getEncryptPassword(String userPassword) {
        String passwordPrefix = "kx";
        return DigestUtils.md5DigestAsHex((passwordPrefix + userPassword).getBytes());
    }

    @Override
    public UserVO getUserToVo(User user) {
        if (ObjUtil.isNull(user)) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> users) {
        if (CollUtil.isEmpty(users)) {
            return new ArrayList<>();
        }
        List<UserVO> collect = users.stream()
                .map(this::getUserToVo)
                .collect(Collectors.toList());
        return collect;

    }

    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequestDTO userQueryRequestDTO) {
        if (userQueryRequestDTO == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = userQueryRequestDTO.getId();
        String userAccount = userQueryRequestDTO.getUserAccount();
        String userName = userQueryRequestDTO.getUserName();
        String userProfile = userQueryRequestDTO.getUserProfile();
        String userRole = userQueryRequestDTO.getUserRole();
        String sortField = userQueryRequestDTO.getSortField();
        String sortOrder = userQueryRequestDTO.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    @Override
    public boolean isAdmin(User user) {
        return user!=null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }
}




